package com.jiayan.controller;

import com.jiayan.model.EbUser;
import com.jiayan.service.EbUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private EbUserService userService;

    @Resource
    private ServletContext application;

    @RequestMapping("/tologin")
    public String tologin(Model model, EbUser ebUser){
        return "/login";
    }

    @RequestMapping("/login")
    public String login(Model model, EbUser ebUser, HttpServletRequest request, HttpServletResponse response){
//        System.out.println("登录的用户名和密码为"+ebUser.getEuUserName()+"\t"+ebUser.getEuPassword());

        EbUser loginUser = userService.login(ebUser.getEuUserName(), ebUser.getEuPassword());

        if(loginUser==null){
            model.addAttribute("error","用户名或密码错误");
            return "/login";
        }
        request.getSession().setAttribute("user",loginUser);

        return "redirect:/index/index";//重定向回首页路径


    }

    @RequestMapping("to_reg")
    public String to_reg(){
        return "reg";
    }

    @RequestMapping(value="/reg",method = RequestMethod.POST)
    public String reg(Model model,String name,String password,String address){
        int num = userService.Insert(name,password,address);
        if(num==0){
            model.addAttribute("error","注册失败");
            return "forward:to_reg";
        }
        return "redirect:/user/tologin";//重定向回登录路径
    }
}

